package com.yhz.openapi.services.impl;

import com.yhz.openapi.dao.MenuMapper;
import com.yhz.openapi.entity.Menu;
import com.yhz.openapi.services.MenuServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServicesImpl implements MenuServices {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> getMenuByUid(Integer id) {
        if (id > 0) {
            //获取用户可以访问的所有的菜单
            List<Menu> all = menuMapper.getMenuByUid(id);
            List<Menu> collect = all.stream().filter(x -> x.getParentId() == null).map(x -> findChildren(x, all)).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    @Override
    public List<Menu> getAllMenuTree() {

        List<Menu> all = menuMapper.getAllMenu();
        //1.找到父菜单
        List<Menu> father=new ArrayList<>();
        for (Menu menu : all) {
            if (menu.getParentId()==null) {
                father.add(menu);
            }
        }
        //2.遍历父菜单
        for (Menu fMenu : father) {
            //创建子菜单的集合
            List<Menu> sMenu=new ArrayList<>();
            //遍历所有菜单节点，找父菜单的子菜单
            for (Menu son : all) {
                if (son.getParentId()!=null&&son.getParentId().equals(fMenu.getId())){
                    sMenu.add(son);
                }
            }
            //把子菜单集合赋值给父节点
            fMenu.setChildren(sMenu);
        }
        return father;
    }



    //查找子级菜单的方法
    public Menu findChildren(Menu m, List<Menu> all) {
        List<Menu> collect = all.stream().filter(x -> x.getParentId() != null && m.getId().equals(x.getParentId()) && x.getType() != 2).map(x -> findChildren(x, all)).collect(Collectors.toList());
        m.setChildren(collect);
        return m;
    }
}
